package xgggh.manage;

import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.f2prateek.rx.preferences2.Preference;
import com.f2prateek.rx.preferences2.RxSharedPreferences;
import com.google.gson.Gson;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import xgggh.model.Auth;
import xgggh.model.Profile;

/**
 * Created by az on 2018/3/27.
 */

public class AuthManager {
    public static final String Token="token";
    public static final String Profile="profile";
    private  static final Auth auth  = new Auth();
    private  static Profile profile  = new Profile();

    public static Auth getAuth() {
        return auth;
    }

    public static boolean isAuth() {
        return !TextUtils.isEmpty(auth.getAccessToken());
    }

    public static Profile getProfile() {
        return profile;
    }


    public static void store(@NonNull RxSharedPreferences sharedPreferences, @NonNull String key , @NonNull Object object) {
        Preference<String> _token = sharedPreferences.getString(key,"{}");
        String _auth= new Gson().toJson(object);
        Observable.just(_auth)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(_token.asConsumer());
    }

    public static void init(@NonNull RxSharedPreferences sharedPreferences, @NonNull String key) {
        Preference<String> _token = sharedPreferences.getString(key,"{}");
        _token.asObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        Auth _auth= new Gson().fromJson(s,Auth.class);
                        saveAuth(sharedPreferences,_auth);
                    }
                });
    }

    public static void saveProfile(@NonNull Profile profile){
        AuthManager.getProfile().setId(profile.getId());
        AuthManager.getProfile().setUserId(profile.getUserId());
        AuthManager.getProfile().setUserName(profile.getUserName());
        AuthManager.getProfile().setNickName(profile.getNickName());
    }

    public static void saveAuth(@NonNull RxSharedPreferences sharedPreferences,@NonNull Auth auth){
        AuthManager.getAuth().setAccessToken(auth.getAccessToken());
        AuthManager.getAuth().setExpiresIn(auth.getExpiresIn());
        AuthManager.getAuth().setRefreshToken(auth.getRefreshToken());
        AuthManager.getAuth().setScope(auth.getScope());
        AuthManager.getAuth().setTokenType(auth.getTokenType());
        AuthManager.getAuth().setUserId(auth.getUserId());
        store(sharedPreferences,Token,AuthManager.getAuth());
    }


}
